package qj.app.trader;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import qj.util.RegexUtil;
import qj.util.funct.F1;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class RuleBuilder extends ParseRule {

	public AttrBuilder attr(String attrName) {
		return new AttrBuilder(attrName, this);
	}
	
	public static class RuleAttr {
		RuleBuilder rule;
		public String name;
	}

	public static class AttrBuilder extends RuleAttr {
		
		public AttrBuilder(String attrName, RuleBuilder rule) {
			this.name = attrName;
			this.rule = rule;
		}

		public AttrBuilder val(String val) {
			MatchPropose matchPropose = matchProposeSure(name, val);
			rule.addKey(val, matchPropose, rule.proposes);
			return this;
		}

		public void valMaybe(String val) {
			MatchPropose matchPropose = matchProposeMaybe(name, val);
			rule.addKey(val, matchPropose, rule.proposes);
		}

		public AttrBuilder prefix(String prefix) {
			// TODO Auto-generated method stub
			return this;
		}

		public AttrBuilder suffix(String string) {
			// TODO Auto-generated method stub
			return this;
		}

	}

	public ParseRule toRule() {
//		System.out.println(proposes);
		return this;
	}

	private void addKey(String key, MatchPropose matchPropose,
			MatchProposes proposes) {
		List<String> normalizedKey = normalizeKey(key);
		proposes.addPropose(normalizedKey, matchPropose);
	}

	private static MatchPropose matchProposeSure(String name, String key) {
		MatchPropose matchPropose = new MatchPropose(name);
		setParser(key, matchPropose);
		return matchPropose;
	}
	
	private static MatchPropose matchProposeMaybe(String name, String key) {
		MatchPropose matchPropose = new MatchPropose(name);
		matchPropose.sure = false;
		setParser(key, matchPropose);
		return matchPropose;
	}

	private static void setParser(String key, MatchPropose matchPropose) {
		// Set parser
		if (hasRegexGroup(key)) {
			matchPropose.setParser(parser(normalize(key)));
		}
	}

	private static F1<String, String> parser(final String pattern) {
		return new F1<String, String>() {public String e(String val) {
			return RegexUtil.getString(pattern, 1, val);
		}};
	}

	private static boolean hasRegexGroup(String normalizedVal) {
		return normalizedVal.contains("(");
	}

	
}
